package com.lyuewei.ringtone.ui;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.elvishew.xlog.XLog;
import com.google.android.material.slider.Slider;
import com.lyuewei.ringtone.PermissionUtils;
import com.lyuewei.ringtone.R;
import com.lyuewei.ringtone.data.RingerSetting;
import com.lyuewei.ringtone.viewmodel.SettingsViewModel;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements RingerSettingAdapter.OnSettingEnabledChangeListener {
    private SettingsViewModel settingsViewModel;
    private RingerSettingAdapter adapter;
    private static final int PERMISSION_REQUEST_CODE = 100;
    // 用于存储对话框中选择的时间
    private int startHour = 0, startMinute = 0, endHour = 23, endMinute = 59;
    private TextView textViewStartTime, textViewEndTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        RecyclerView recyclerView = findViewById(R.id.recyclerViewSettings);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true); // 如果列表项高度固定，可以优化性能

        adapter = new RingerSettingAdapter();
        recyclerView.setAdapter(adapter);
        // 设置启用状态改变监听器
        adapter.setOnSettingEnabledChangeListener(this);

        // 获取 ViewModel
        settingsViewModel = new ViewModelProvider(this).get(SettingsViewModel.class);
        settingsViewModel.init();
        // 观察 LiveData，当数据变化时更新列表
        settingsViewModel.getAllSettings().observe(this, settings -> {
            // 当数据库中的设置列表变化时，更新适配器的数据
            XLog.d("Settings updated: " + settings);
            adapter.submitList(settings);
        });

        // "添加设置" 按钮点击事件
        Button buttonAddSetting = findViewById(R.id.buttonAddSetting);
        buttonAddSetting.setOnClickListener(v -> {
            // 添加新设置时，重置默认时间
            startHour = 0;
            startMinute = 0;
            endHour = 23;
            endMinute = 59;
            showAddEditSettingDialog(null); // 传入 null 表示添加新设置
        });

        // 处理列表项点击（用于修改）
    adapter.setOnItemLongClickListener(setting -> {
        // 编辑设置时，初始化时间为现有设置的时间
        startHour = setting.getStartHour();
        startMinute = setting.getStartMinute();
        endHour = setting.getEndHour();
        endMinute = setting.getEndMinute();
        showAddEditSettingDialog(setting);
    });

        // 实现滑动删除
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.LEFT ) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false; // 不处理拖拽
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                RingerSetting settingToDelete = adapter.getSettingAt(position);

                // 对于 ID 为 1 的全局设置，不允许删除
                if (settingToDelete.getId() == 1) {
                    Toast.makeText(MainActivity.this, "无法删除全局设置", Toast.LENGTH_SHORT).show();
                    adapter.notifyItemChanged(position); // 撤销滑动
                    return;
                }

                // 弹出确认删除对话框
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("删除设置")
                        .setMessage("确定要删除此设置吗？")
                        .setPositiveButton("删除", (dialog, which) -> {
                            settingsViewModel.delete(settingToDelete);
                            Toast.makeText(MainActivity.this, "设置已删除", Toast.LENGTH_SHORT).show();
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 用户取消删除，撤销滑动操作
                            adapter.notifyItemChanged(position);
                        })
                        .create()
                        .show();
            }
        }).attachToRecyclerView(recyclerView);
        checkAndRequestPermissions();

    }


    // 显示添加或修改设置的对话框
    private void showAddEditSettingDialog(RingerSetting settingToEdit) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_edit_setting, null); // 使用更新后的对话框布局
        builder.setView(dialogView);

        EditText editTextPhoneNumber = dialogView.findViewById(R.id.editTextPhoneNumber);
        EditText editTextName = dialogView.findViewById(R.id.editTextName);
        Slider sliderVolume = dialogView.findViewById(R.id.sliderVolume); // 滑块
        TextView textViewVolumeValue = dialogView.findViewById(R.id.textViewVolumeValue); // 显示滑块值的 TextView
        Slider sliderInterval = dialogView.findViewById(R.id.sliderInterval); // 滑块
        TextView textViewIntervalValue = dialogView.findViewById(R.id.textViewIntervalValue);
        Slider sliderTimes = dialogView.findViewById(R.id.sliderTimes); // 滑块
        TextView textViewTimesValue = dialogView.findViewById(R.id.textViewTimesValue);
        Switch switchEnabled = dialogView.findViewById(R.id.switchEnabled);

        // 时间选择相关的 TextView 和 Button
        textViewStartTime = dialogView.findViewById(R.id.textViewStartTime);
        Button buttonSelectStartTime = dialogView.findViewById(R.id.buttonSelectStartTime);
        textViewEndTime = dialogView.findViewById(R.id.textViewEndTime);
        Button buttonSelectEndTime = dialogView.findViewById(R.id.buttonSelectEndTime);

        boolean isEditing = (settingToEdit != null);
        builder.setTitle(isEditing ? "修改设置" : "添加设置");

        // 设置滑块的最大最小值和步长
        sliderVolume.setValueFrom(0);
        sliderVolume.setValueTo(100);
        sliderVolume.setStepSize(1);

        // 间隔设置为毫秒，可以根据需要调整范围和步长
        sliderInterval.setValueFrom(0); // 例如最小间隔 1 分
        sliderInterval.setValueTo(60); // 例如最大间隔 60 分
        sliderInterval.setStepSize(1); // 例如步长 1 分

        // 次数设置为整数
        sliderTimes.setValueFrom(0);
        sliderTimes.setValueTo(20); // 例如最多响铃 10 次
        sliderTimes.setStepSize(1);

        // 设置滑块值变化监听器，更新旁边的 TextView
        sliderVolume.addOnChangeListener((slider, value, fromUser) -> textViewVolumeValue.setText(String.format(Locale.getDefault(), "%d%%", (int) value)));
        sliderInterval.addOnChangeListener((slider, value, fromUser) -> textViewIntervalValue.setText(String.format(Locale.getDefault(), " %d分", (int) value)));
        sliderTimes.addOnChangeListener((slider, value, fromUser) -> textViewTimesValue.setText(String.format(Locale.getDefault(), " %d次", (int) value)));

        // 设置时间选择按钮的点击事件
        buttonSelectStartTime.setOnClickListener(v -> showTimePickerDialog(true));
        buttonSelectEndTime.setOnClickListener(v -> showTimePickerDialog(false));

        // 如果是修改模式，填充现有数据
        if (isEditing) {
            editTextPhoneNumber.setText(settingToEdit.getPhone());
            editTextName.setText(settingToEdit.getName());

            // 设置滑块的当前值
            sliderVolume.setValue(settingToEdit.getVolume());
            // 立即更新 TextView 显示当前值
            textViewVolumeValue.setText(String.format(Locale.getDefault(), " %d%%", settingToEdit.getVolume()));

            sliderInterval.setValue(settingToEdit.getInterval());
            textViewIntervalValue.setText(String.format(Locale.getDefault(), " %d分", settingToEdit.getInterval()));

            sliderTimes.setValue(settingToEdit.getTimes());
            textViewTimesValue.setText(String.format(Locale.getDefault(), " %d次", settingToEdit.getTimes()));

            switchEnabled.setChecked(settingToEdit.isEnabled());

            // 设置现有的时间范围到 TextViews
            startHour = settingToEdit.getStartHour();
            startMinute = settingToEdit.getStartMinute();
            endHour = settingToEdit.getEndHour();
            endMinute = settingToEdit.getEndMinute();
            textViewStartTime.setText(String.format(Locale.getDefault(), "%02d:%02d", startHour, startMinute));
            textViewEndTime.setText(String.format(Locale.getDefault(), "%02d:%02d", endHour, endMinute));
        } else {
            // 添加新设置时，设置滑块默认值并更新 TextView
            sliderVolume.setValue(50); // 默认音量 50%
            textViewVolumeValue.setText(String.format(Locale.getDefault(), " %d%%", 50));

            sliderInterval.setValue(10); // 默认间隔 5 秒
            textViewIntervalValue.setText(String.format(Locale.getDefault(), "%d分", 10));

            sliderTimes.setValue(3); // 默认次数 3 次
            textViewTimesValue.setText(String.format(Locale.getDefault(), " %d次", 3));

            switchEnabled.setChecked(true); // 新增设置默认启用

            // 设置默认时间范围并更新 TextViews
            textViewStartTime.setText(String.format(Locale.getDefault(), "%02d:%02d", startHour, startMinute));
            textViewEndTime.setText(String.format(Locale.getDefault(), "%02d:%02d", endHour, endMinute));
        }

        // 排除全局设置（ID 为 1）对电话号码和名称的编辑
        if (isEditing && settingToEdit.getId() == 1) {
            editTextPhoneNumber.setEnabled(false);
            editTextName.setEnabled(false);
        } else {
            editTextPhoneNumber.setEnabled(true);
            editTextName.setEnabled(true);
        }
        builder.setPositiveButton(isEditing ? "保存" : "添加", null);
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        AlertDialog dialog = builder.create();

        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String phoneNumber = editTextPhoneNumber.getText().toString();
                if (settingToEdit!=null&&settingToEdit.getId()>1&&phoneNumber.isEmpty()) {
                    Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                String name = editTextName.getText().toString();
                int volume = (int) sliderVolume.getValue();
                long interval = (long) sliderInterval.getValue();
                int times = (int) sliderTimes.getValue();
                boolean enabled = switchEnabled.isChecked();

                // 获取选择的时间范围
                int finalStartHour = startHour;
                int finalStartMinute = startMinute;
                int finalEndHour = endHour;
                int finalEndMinute = endMinute;

                if (isEditing) {
                    // 修改现有设置
                    settingToEdit.setPhone(phoneNumber);
                    settingToEdit.setName(name);
                    settingToEdit.setVolume(volume);
                    settingToEdit.setInterval(interval);
                    settingToEdit.setTimes(times);
                    settingToEdit.setEnabled(enabled);
                    settingToEdit.setStartHour(finalStartHour); // 保存时间范围
                    settingToEdit.setStartMinute(finalStartMinute); // 保存时间范围
                    settingToEdit.setEndHour(finalEndHour); // 保存时间范围
                    settingToEdit.setEndMinute(finalEndMinute); // 使用正确的对象引用
                    settingsViewModel.update(settingToEdit);
                  adapter.notifyItemChanged(adapter.getCurrentList().indexOf(settingToEdit));
                    Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
                } else {
                    // 添加新设置
                    RingerSetting newSetting = new RingerSetting(phoneNumber, name, volume, interval, times,
                            finalStartHour, finalEndHour, finalStartMinute, finalEndMinute, enabled); // 包含时间范围
                    settingsViewModel.insert(newSetting);
                    Toast.makeText(this, "设置已添加", Toast.LENGTH_SHORT).show();
                }
                dialog.dismiss();
            });
        });
        dialog.show();
    }

    private void showTimePickerDialog(boolean isStartTime) {
        int initialHour = isStartTime ? startHour : endHour;
        int initialMinute = isStartTime ? startMinute : endMinute;

        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    if (isStartTime) {
                        startHour = hourOfDay;
                        startMinute = minute;
                        textViewStartTime.setText(String.format(Locale.getDefault(), "%02d:%02d", startHour, startMinute));
                    } else {
                        endHour = hourOfDay;
                        endMinute = minute;
                        textViewEndTime.setText(String.format(Locale.getDefault(), "%02d:%02d", endHour, endMinute));
                    }
                },
                initialHour,
                initialMinute,
                true // true 表示 24 小时制，false 表示 12 小时制带 AM/PM
        );
        timePickerDialog.show();
    }
    private void checkAndRequestPermissions() {
        String[] permissions = {
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.READ_CALL_LOG,
                android.Manifest.permission.ACCESS_NOTIFICATION_POLICY // 如果需要动态请求勿扰模式权限
        };

        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (allPermissionsGranted) {
            // 权限已授予，可以执行需要这些权限的操作
            XLog.d("所需权限已全部授予");
           // Toast.makeText(this, "所需权限已全部授予", Toast.LENGTH_SHORT).show();
        } else {
            // 权限未全部授予，请求权限
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }

        // 特别检查并请求勿扰模式权限 (ACCESS_NOTIFICATION_POLICY)
        // 这个权限的请求方式有点特殊，不是通过 ActivityCompat.requestPermissions()
        if (!PermissionUtils.hasDndPermission(this)) {
            Toast.makeText(this, "请授予勿扰模式访问权限", Toast.LENGTH_LONG).show();
            // 引导用户去设置页面授予权限
            PermissionUtils.requestDndPermission(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                // 所有权限都已授予
                XLog.d("权限已授予");
               Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
                // 可以执行需要这些权限的操作
            } else {
                // 用户拒绝了部分或全部权限
                Toast.makeText(this, "部分或全部权限被拒绝，功能可能受限", Toast.LENGTH_LONG).show();
                // 考虑是否需要向用户解释为什么需要这些权限，或者禁用相关功能
            }
        }
    }

    @Override
    public void onSettingEnabledChange(RingerSetting setting, boolean isEnabled) {
             setting.setEnabled(isEnabled);
            settingsViewModel.update(setting); // 调用 ViewModel 更新数据库

        Toast.makeText(this, setting.getName() + (isEnabled ? " 已启用" : " 已禁用"), Toast.LENGTH_SHORT).show();
    }
}